package me.fung.wubi.base.io

import mu.KotlinLogging
import java.io.File
import java.nio.charset.Charset
import java.util.Arrays

private val logger = KotlinLogging.logger { }

/**
 * 自动读取签名判断字符集
 */
fun File.autoReadLines(defaultCharset: Charset? = null): List<String> {
    val buffer = ByteArray(4) { 0 }
    inputStream().use { it.read(buffer) }
    val charset = buffer.charset() ?: defaultCharset ?: Charset.forName(System.getProperty("native.encoding"))
    logger.debug { "${this.path}\t${charset}" }
    return readLines(charset = charset).mapIndexed { index, str ->
        if (index == 0) {
            val bytes = str.toByteArray(charset)
            val sign = charsetMap.firstNotNullOfOrNull {
                if (it.value == charset) it.key else null
            }?.reversed()
            if (sign != null) {
                val newBytes: ByteArray = Arrays.copyOfRange(bytes, sign.size, bytes.size)
                newBytes.toString(charset)
            } else str
        } else str
    }
}